package GUI;

import BE.BEContrasenha;
import BE.BEEmpleado;
import BE.BEParametrosSeguridad;
import BE.BEPerfil;
import BE.BEUsuario;
import BL.BLContrasenha;
import BL.BLEmpleado;
import BL.BLParametrosSeguridad;
import BL.BLPerfil;
import BL.BLUsuario;
import java.awt.Dimension;

import javax.swing.JOptionPane;
import java.awt.Toolkit;
import java.util.*;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUIfrmLogin.java
 *
 * Created on 15-oct-2011, 21:25:37
 */
/**
 *
 * @author PUKI
 */
public class GUIfrmLogin extends javax.swing.JFrame {
    static final long ONE_HOUR = 60 * 60 * 1000L;
    BLUsuario objGestorUsuario;
    BLContrasenha objGestorContrasenha;
    BLEmpleado objGestorEmpleado;
    BLPerfil objGestorPerfil;
    BLParametrosSeguridad objGestorParametros;
    BEUsuario objUsuario;
    BEPerfil objPerfil;
    BEContrasenha objContrasenha;
    BEEmpleado objEmpleado;
    //private ImageIcon imageIcon = new ImageIcon(getClass().getResource("/Imagenes/hybrid-badage.jpg"));  
    int intentos=0;
    //ImageIcon imagen = new ImageIcon("/Imagenes/hybrid-logo.jpg");
    //JLabel etiqueta = new JLabel(imagen);
    
    /** Creates new form GUIfrmLogin */
    public GUIfrmLogin() {
        objGestorPerfil= new BLPerfil();
        objGestorContrasenha = new BLContrasenha();
        objGestorUsuario = new BLUsuario();
        objGestorParametros= new BLParametrosSeguridad();
        //objGestorEmpleado= new BLEmpleado();
        objUsuario= null;
        objPerfil=null;
        objContrasenha=null;
        objEmpleado= null;
        
        
        initComponents();
        
        this.setLocationRelativeTo(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int height = screenSize.height;
        int width = screenSize.width;
        this.setLocation(width/2-this.getWidth()/2, height/2-this.getHeight()/2);
 
      
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblLogin = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        txtUsuario = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtClave = new javax.swing.JPasswordField();
        btnCancelar = new javax.swing.JButton();
        btnAceptar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setForeground(new java.awt.Color(204, 204, 204));
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                formKeyTyped(evt);
            }
        });

        lblLogin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/logoFinal.jpg"))); // NOI18N
        lblLogin.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyTyped(evt);
            }
        });

        jLabel1.setText("USUARIO:");

        jLabel2.setText("CLAVE:");

        txtClave.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtClaveKeyTyped(evt);
            }
        });

        btnCancelar.setText("CANCELAR");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnAceptar.setText("ACEPTAR");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(3, 3, 3)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(txtClave, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(btnAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancelar)))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAceptar, btnCancelar});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAceptar)
                    .addComponent(btnCancelar))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAceptar, btnCancelar});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(lblLogin)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(22, Short.MAX_VALUE)
                .addComponent(lblLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
// TODO add your handling code here:
    
    
    if ("".equals(txtUsuario.getText()))
         JOptionPane.showMessageDialog(null,"Debe ingresar un usuario","Ingreso al sistema",JOptionPane.ERROR_MESSAGE);
    else if ("".equals(txtClave.getText()))
         JOptionPane.showMessageDialog(null,"Debe ingresar una contraseña" ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);    
    else if(ingresar(txtUsuario.getText(),txtClave.getText()))
    {
                
            Date aux = new Date();
//            JOptionPane.showMessageDialog(null,"Dias entre: "+daysBetween(objContrasenha.getFechaCreacion(),aux)+"; Dias para la rotacion: "+objGestorParametros.getObjParametros().getTiempoRotacion()+ ""
//                 ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);
            if (daysBetween(objContrasenha.getFechaCreacion(), aux)>=objGestorParametros.getObjParametros().getTiempoRotacion())
            {
                GUICambiarContrasenha frmCambiarContrasenha= new GUICambiarContrasenha(this, rootPaneCheckingEnabled,objUsuario);
                this.setVisible(false);
                frmCambiarContrasenha.setVisible(true);
                
                
            }
        
            objGestorUsuario.actualizarIntentosFallidos(objUsuario, 0);
            GUIfrmPrincipal frmMenu = new GUIfrmPrincipal(objPerfil,objUsuario);
            this.setVisible(false);
            frmMenu.setVisible(true);
            this.dispose();
     }
    
    if (objUsuario!=null)
    {
        if(objGestorUsuario.obtenerIntentosFallidos(objUsuario)>=objGestorParametros.getObjParametros().getnIntentosFallidos())
    {
            objGestorUsuario.actualizarEstadoAInactivo(objUsuario);
    }
       
    }
     
  
}//GEN-LAST:event_btnAceptarActionPerformed

private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
    this.dispose();
    // TODO add your handling code here:
}//GEN-LAST:event_btnCancelarActionPerformed

private void formKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyTyped
        int key = evt.getKeyChar();
        
        if (key == 10) {
                if ("".equals(txtUsuario.getText()))
         JOptionPane.showMessageDialog(null,"Debe ingresar un usuario"
                 ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);
    else if ("".equals(txtClave.getText()))
         JOptionPane.showMessageDialog(null,"Debe ingresar una contraseña"
                 ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);    
    else if(ingresar(txtUsuario.getText(),txtClave.getText()))
    {
        
            Date aux = new Date();
//            JOptionPane.showMessageDialog(null,"Dias entre: "+daysBetween(objContrasenha.getFechaCreacion(),aux)+"; Dias para la rotacion: "+objGestorParametros.getObjParametros().getTiempoRotacion()+ ""
//                 ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);
            if (daysBetween(objContrasenha.getFechaCreacion(), aux)>=objGestorParametros.getObjParametros().getTiempoRotacion())
            {
                GUICambiarContrasenha frmCambiarContrasenha= new GUICambiarContrasenha(this, rootPaneCheckingEnabled,objUsuario);
                this.setVisible(false);
                frmCambiarContrasenha.setVisible(true);
                
                
            }
                
            objGestorUsuario.actualizarIntentosFallidos(objUsuario, 0);
            GUIfrmPrincipal frmMenu = new GUIfrmPrincipal(objPerfil,objUsuario);
            this.setVisible(false);
            frmMenu.setVisible(true);
            this.dispose();
     }
    
   if (objUsuario!=null)
    {
        if(objGestorUsuario.obtenerIntentosFallidos(objUsuario)>=objGestorParametros.getObjParametros().getnIntentosFallidos())
    {
            objGestorUsuario.actualizarEstadoAInactivo(objUsuario);
    }
       
    }
        } 
            
}//GEN-LAST:event_formKeyTyped

private void txtUsuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyTyped
        int key = evt.getKeyChar();
        
        if (key == 10) {
            if ("".equals(txtUsuario.getText()))
             JOptionPane.showMessageDialog(null,"Debe ingresar un usuario"
                 ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);
            else if ("".equals(txtClave.getText()))
            JOptionPane.showMessageDialog(null,"Debe ingresar una contraseña"
                 ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);    
            else
    if(ingresar(txtUsuario.getText(),txtClave.getText()))
                
    {
            Date aux = new Date();
//            JOptionPane.showMessageDialog(null,"Dias entre: "+daysBetween(objContrasenha.getFechaCreacion(),aux)+"; Dias para la rotacion: "+objGestorParametros.getObjParametros().getTiempoRotacion()+ ""
//                 ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);
            if (daysBetween(objContrasenha.getFechaCreacion(), aux)>=objGestorParametros.getObjParametros().getTiempoRotacion())
            {
                GUICambiarContrasenha frmCambiarContrasenha= new GUICambiarContrasenha(this, rootPaneCheckingEnabled,objUsuario);
                this.setVisible(false);
                frmCambiarContrasenha.setVisible(true);
                
                
            }
                
            objGestorUsuario.actualizarIntentosFallidos(objUsuario, 0);
            GUIfrmPrincipal frmMenu = new GUIfrmPrincipal(objPerfil,objUsuario);
            this.setVisible(false);
            frmMenu.setVisible(true);
            this.dispose();
     }
    
     if (objUsuario!=null)
    {
        if(objGestorUsuario.obtenerIntentosFallidos(objUsuario)>=objGestorParametros.getObjParametros().getnIntentosFallidos())
    {
            objGestorUsuario.actualizarEstadoAInactivo(objUsuario);
    }
       
    }
        } 
    // TODO add your handling code here:
}//GEN-LAST:event_txtUsuarioKeyTyped

private void txtClaveKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtClaveKeyTyped
        int key = evt.getKeyChar();
        
        if (key == 10) {
            if ("".equals(txtUsuario.getText()))
         JOptionPane.showMessageDialog(null,"Debe ingresar un usuario"
                 ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);
    else if ("".equals(txtClave.getText()))
         JOptionPane.showMessageDialog(null,"Debe ingresar una contraseña"
                 ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);    
    else if(ingresar(txtUsuario.getText(),txtClave.getText()))
    {
            Date aux = new Date();
//            JOptionPane.showMessageDialog(null,"Dias entre: "+daysBetween(objContrasenha.getFechaCreacion(),aux)+"; Dias para la rotacion: "+objGestorParametros.getObjParametros().getTiempoRotacion()+ ""
//                 ,"Ingreso al sistema",JOptionPane.ERROR_MESSAGE);
            if (daysBetween(objContrasenha.getFechaCreacion(), aux)>=objGestorParametros.getObjParametros().getTiempoRotacion())
            {
                GUICambiarContrasenha frmCambiarContrasenha= new GUICambiarContrasenha(this, rootPaneCheckingEnabled,objUsuario);
                this.setVisible(false);
                frmCambiarContrasenha.setVisible(true);
                
                
            }
                
            objGestorUsuario.actualizarIntentosFallidos(objUsuario, 0);
            GUIfrmPrincipal frmMenu = new GUIfrmPrincipal(objPerfil,objUsuario);
            this.setVisible(false);
            frmMenu.setVisible(true);
            this.dispose();
     }
    
        if (objUsuario!=null)
    {
        if(objGestorUsuario.obtenerIntentosFallidos(objUsuario)>=objGestorParametros.getObjParametros().getnIntentosFallidos())
    {
            objGestorUsuario.actualizarEstadoAInactivo(objUsuario);
    }
       
    }
        } 
}//GEN-LAST:event_txtClaveKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUIfrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUIfrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUIfrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUIfrmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        
        
           
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new GUIfrmLogin().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblLogin;
    private javax.swing.JPasswordField txtClave;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables

    private boolean ingresar(String Usuario, String Contrasenha) {
        objGestorPerfil.cargar();
        objGestorContrasenha.cargar();
        objGestorUsuario.cargar();
        objGestorParametros.cargar();
                
        objUsuario=objGestorUsuario.buscarUsuario(Usuario);
        
        
        
        if ((objUsuario!=null) )
        {
            objPerfil=objGestorPerfil.buscarIdPerfil(objUsuario.getIdPerfil());
            objContrasenha= objGestorContrasenha.obtenerContrasenhaActualIdUsuario(objUsuario.getIdUsuario());
            intentos = objGestorUsuario.obtenerIntentosFallidos(objUsuario);
            System.out.println(intentos);
            if(Contrasenha.equals(objContrasenha.getContrasenha()))
            {
                if(objPerfil.getEstado().equals("ACTIVO"))
                {
                    if (objUsuario.getEstado().equals("ACTIVO"))
                    {
                        return true;
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null,"Usuario y/o contraseña no valida.","Ingreso al sistema",JOptionPane.INFORMATION_MESSAGE);
                        objGestorUsuario.actualizarIntentosFallidos(objUsuario, intentos+1);
                        return false;
                    }
                }
                else
                {
                    JOptionPane.showMessageDialog(null,"Usuario y/o contraseña no valida.","Ingreso al sistema",JOptionPane.INFORMATION_MESSAGE);
                    objGestorUsuario.actualizarIntentosFallidos(objUsuario, intentos+1);
                    return false;
                }
            }
            else
            {
                JOptionPane.showMessageDialog(null,"Usuario y/o contraseña no valida.","Ingreso al sistema",JOptionPane.INFORMATION_MESSAGE);
                objGestorUsuario.actualizarIntentosFallidos(objUsuario, intentos+1);
                return false;
            }
        }
        else
        {
            JOptionPane.showMessageDialog(null,"Usuario y/o contraseña no valida.","Ingreso al sistema",JOptionPane.INFORMATION_MESSAGE);
            //objGestorUsuario.actualizarIntentosFallidos(objUsuario, intentos+1);
            return false;
        }
        
        
    }
    
    public static long daysBetween(Date d1, Date d2){
    return ( (d2.getTime() - d1.getTime() + ONE_HOUR) /
                  (ONE_HOUR * 24));
  }
}

    

    

    
        
        
    

   

